package org.goobs.csp;



import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public abstract class UniquenessConstraint implements IConstraint{

	protected CSPVariable var;
	
	public UniquenessConstraint(CSPVariable var){
		this.var = var;
	}
	
	public abstract boolean thisVarQualifies();
	
	@SuppressWarnings("unchecked")
	/**
	 * This should be true in the case that the two variables are compatible.
	 * That is, true if the other variable is unique from this variable
	 */
	public abstract boolean otherVarUnique(CSPVariable otherVar);
	
	
	@SuppressWarnings("unchecked")
	public Collection <ICSPArc> generateArcs(CSP csp){
		Collection rtn = new ArrayList <ICSPArc>();
		
		Iterator <CSPVariable> iter = csp.variableIterator();
		while(iter.hasNext()){
			final CSPVariable <?> term = iter.next();
			if(term.equals(var)){
				continue;
			}
			
			ICSPArc arc = new ICSPArc() {
				@Override
				public boolean isOK() {
					if(var.getValue() == null){
						return true;
					}else if(thisVarQualifies()){
						if(term.getValue() == null){
							return true;
						}else{
							return otherVarUnique(term);
						}
					}else{
						return true;
					}
				}
				@Override
				public CSPVariable getTail() {
					return var;
				}
				@Override
				public CSPVariable getHead() {
					return term;
				}
				@Override
				public String toString(){
					return "uniqueness arc: " + this.getTail() + " : " + this.getHead();
				}
			};
			rtn.add(arc);
		}
		
		return rtn;
	}
}
